package com.ermao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ermao.mapper.UserMapper;
import com.ermao.pojo.User;
import com.ermao.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author Ermao
 * Date: 2021/9/3 13:13
 */
@Service
public class UserServiceImpl implements UserService {

	@Resource
	private UserMapper userMapper;

	@Override
	public Boolean isExistUserByAccountNumber(Integer accountNumber) {
		QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
		userQueryWrapper.eq("account_number", accountNumber);
		User user = userMapper.selectOne(userQueryWrapper);
		return user != null;
	}

	@Override
	public Boolean registerANewUser(Integer accountNumber, String password, String email) {
		User user = new User();
		user.setAccountNumber(accountNumber);
		user.setPassword(password);
		user.setEmail(email);
		return userMapper.insert(user) > 0;
	}

	@Override
	public Boolean login(Integer accountNumber, String password, HttpServletRequest request) {
		QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
		userQueryWrapper.eq("account_number", accountNumber);
		userQueryWrapper.eq("password", password);
		User user = userMapper.selectOne(userQueryWrapper);
		return user != null;
	}

	@Override
	public User selectAUserByAccountNumber(Integer accountNumber) {
		QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
		userQueryWrapper.select("user_id", "nickname", "days");
		userQueryWrapper.eq("account_number", accountNumber);
		return userMapper.selectOne(userQueryWrapper);
	}

	@Override
	public User selectAUserByUserId(Integer userId) {
		return userMapper.selectById(userId);
	}

	@Override
	public Boolean updateUserNickname(User user, String nickname) {
		user.setNickname(nickname);
		return userMapper.updateById(user) > 0;
	}

	@Override
	public Boolean updateUserPassword(User user, String oldPassword, String newPassword) {
		if (!user.getPassword().equals(oldPassword)) {
			return Boolean.FALSE;
		}
		user.setPassword(newPassword);
		return userMapper.updateById(user) > 0;
	}
}
